<template>
  <div class="app-container">
    <el-card>
      <title-line title="基本信息" />
      <el-form ref="elForm" :model="formData" :rules="rules" label-width="110px">
        <el-row>
          <el-col :lg="16" :xl="10">
            <el-form-item label="礼品券名称：" prop="name">
              <el-input v-model.trim="formData.name" placeholder="请输入礼品券名称（1-15）" />
            </el-form-item>
            <el-form-item label="券码开头：" prop="prefix">
              <el-input v-model="formData.prefix" placeholder="请输入礼品券开头（1-10）" />
              <p class="ft-12">仅限大写字母开头，比如SF,TBTJ等</p>
            </el-form-item>
            <el-form-item label="券码总数：" prop="total">
              <el-input
                v-model.number="formData.total"
                placeholder="请输入礼品券总张数（5-50000）"
              />
            </el-form-item>
            <el-form-item label="积分列表：" required>
              <el-button type="text" @click="addCouponClick">添加奖品+</el-button>
              <PageTable :columns="columns" :data="giftCouponConfigBackPos" />
            </el-form-item>
            <el-form-item label="未中奖：" prop="notPrizeRemind">
              <el-input v-model.trim="formData.notPrizeRemind" placeholder="请输入未中奖提示文字" />
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input v-model="formData.sort" />
              <p class="ft-12" style="color: #999">分类排序数字越小越靠前</p>
            </el-form-item>
            <el-form-item label="是否启用：" prop="isEnable" required>
              <el-radio-group v-model="formData.isEnable">
                <el-radio v-for="(item, index) in IS_STATUS" :key="index" :label="item.value">{{
                  item.label
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item style="text-align: center">
              <el-button @click="resetForm"> 取消 </el-button>
              <el-button type="primary" @click="submitForm" :loading="loading"> 确定 </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <AddCouponPopup
      v-if="dialogVisible"
      :row-id="rowId"
      :row-data="rowData"
      :count-total="countTotal"
      :dialogVisible.sync="dialogVisible"
      v-model="giftCouponConfigBackPos"
      @update="rowData = null"
    />
  </div>
</template>

<script>
import _ from 'lodash'
import rules from './rules'
import { IS_STATUS } from '@/enum'
import AddCouponPopup from './components/AddCouponPopup.vue'
export default {
  name: 'AddCoupon',
  components: {
    AddCouponPopup
  },
  data() {
    return {
      loading: false,
      rowId: '',
      rowData: null,
      dialogVisible: false,
      giftCouponConfigBackPos: [],
      formData: {
        name: '',
        prefix: '',
        total: '',
        notPrizeRemind: '',
        sort: 99,
        isEnable: false,
        giftCouponConfigBackPos: []
      },
      countTotal: 0,
      columns: [
        {
          prop: 'couponName',
          label: '名称'
        },
        {
          prop: 'couponIntegral',
          label: '积分值'
        },
        {
          prop: 'couponsItemTotal',
          label: '数量'
        },
        {
          label: '中奖概率',
          render: (h, { row }) => {
            return <div>{row.acquireRatio}%</div>
          }
        },
        {
          label: '操作',
          render: (h, { row }) => {
            return (
              <div>
                <el-button
                  type="text"
                  onClick={() => {
                    this.updateDrawList(row)
                  }}
                >
                  编辑
                </el-button>
                <el-button
                  type="text"
                  onClick={() => {
                    this.deleteDrawList(row.id)
                  }}
                >
                  删除
                </el-button>
              </div>
            )
          }
        }
      ]
    }
  },
  computed: {
    IS_STATUS() {
      return IS_STATUS
    },
    id() {
      return this.$route.query.id
    },
    rules() {
      return rules
    },
    // 奖品中奖概率
    couponCount() {
      if (!this.giftCouponConfigBackPos.length) return 0
      return this.giftCouponConfigBackPos?.reduce((prev, next) => {
        return Number(prev) + Number(next.acquireRatio)
      }, [])
    }
  },
  watch: {
    'formData.total'(value) {
      if (value) {
        this.giftCouponConfigBackPos = this.giftCouponConfigBackPos.map(item => {
          return {
            ...item,
            couponsItemTotal: parseInt(value * (item.acquireRatio / 100))
          }
        })
      }
    }
  },
  methods: {
    addCouponClick() {
      if (this.couponCount > 100) return this.$message.error('目前中奖概率超过100%，无法添加！')
      this.rowId = '' // 新增不需要回显

      // 带入子组件计算
      if (this.formData.total) {
        this.countTotal = this.formData.total
      }
      this.dialogVisible = true
    },
    // 删除中奖选项
    deleteDrawList(id) {
      let currIndex = this.giftCouponConfigBackPos.findIndex(item => item.id === id)
      this.giftCouponConfigBackPos.splice(currIndex, 1)
    },
    updateDrawList(row) {
      this.rowId = row.id || row.uuid
      this.rowData = row
      this.countTotal = this.formData.total
      this.dialogVisible = true
    },
    getParams() {
      const params = {
        ...this.formData,
        giftCouponConfigBackPos: this.giftCouponConfigBackPos.map(item => {
          delete item.uuid
          return {
            ...item,
            acquireRatio: item.acquireRatio + ''
          }
        })
      }
      return params
    },
    // 新增中奖选项
    addCoupon: _.debounce(async function () {
      this.loading = true
      const params = this.getParams()
      try {
        const { status, msg } = await this.$http.coupon.voucherApi.addCoupon(params)
        if (status === 200) {
          this.$message.success('新增成功！')
          this.$router.back(-1)
        } else {
          this.$message.error(msg)
        }
      } finally {
        this.loading = false
      }

      this.loading = false
    }, 500),
    // 提交
    submitForm() {
      this.$refs['elForm'].validate(async valid => {
        if (!valid) return
        if (!this.giftCouponConfigBackPos.length)
          return this.$message.error('最少添加1个中奖选项！')
        if (this.couponCount > 100) return this.$message.error('目前中奖概率超过100%，无法添加！')
        this.addCoupon()
      })
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
      this.$router.back(-1)
    }
  }
}
</script>
